from random import randint
from lib.ZNode import ZNode
from lib.res.fun import _create_image


class Sprite ( ZNode ) :
	def __init__ ( self , father , image , pos , speed_x , speed_y , life ) :
		super ( Sprite , self ).__init__ ( father )
		self.type = type

		self.life = life
		self.time = 0
		self.type = { }
		self.type [ 0 ] = 'right'
		self.type [ 1 ] = 'bottom'

		if speed_x < 0 :
			self.type [ 0 ] = 'left'
		else :
			self.type [ 0 ] = 'right'
		self.speed_x = randint ( speed_x [ 0 ] , speed_x [ 1 ] )
		if speed_y < 0 :
			self.type [ 1 ] = 'top'
		else :
			self.type [ 1 ] = 'bottom'
		self.speed_y = randint ( speed_y [ 0 ] , speed_y [ 1 ] )
		self.second = 22 / 1000.00

		self.image = _create_image ( image )
		self.rect = self.image.get_rect ( )
		self.image.set_alpha ( randint ( 160 , 255 ) )

		self.director = randint ( 0 , 30 )
		self.rect.topleft = pos
		self.alpha_speed = randint ( min ( 6 , 255 // 30 ) , 255 // 30 )
		self.alpha = self.image.get_alpha ( )

	def overlife ( self ) :
		self.time += self.second
		if self.time > self.life or self.image.get_alpha ( ) <= 0 :
			return True
		else :
			return False

	def draw ( self ) :

		if self.type [ 0 ] == 'right' :
			self.rect.x += self.speed_x
		elif self.type [ 0 ] == 'left' :
			self.rect.x -= self.speed_x
		if self.type [ 1 ] == 'bottom' :
			self.rect.y += self.speed_y
		elif self.type [ 1 ] == 'top' :
			self.rect.y -= self.speed_y

		self.alpha -= self.alpha_speed
		if self.alpha > 0 :
			self.image.set_alpha ( self.alpha )

		self.father.screen.blit ( self.image , self.rect.topleft )


class PSO ( ZNode ) :
	def __init__ ( self , father , filename , pos = [ 0 , 0 ] , max = 24 , speed_x = [ -4 , 1 ] , speed_y = [ -3 , 0 ] ,
	               area = 10 ,
	               life = .6 ) :
		super ( PSO , self ).__init__ ( father )
		self._pos = pos
		self.max = max
		self.life = life
		self._running = True
		self.sprites = [ ]
		self.current = 0
		self.image = filename
		self.random_area = area
		self.speed_x = speed_x
		self.speed_y = speed_y

	def draw ( self ) :
		pos = [ randint ( 0 , self.random_area ) + self._pos [ 0 ] ,
		        randint ( 0 , self.random_area ) + self._pos [ 1 ] ]
		if self._running :
			if len ( self.sprites ) <= self.max :
				self.sprites.append ( Sprite ( self , self.image , pos , self.speed_x , self.speed_y , self.life ) )
				self.current += 1

			if len ( self.sprites ) :
				for x in self.sprites :
					if x.overlife ( ) :
						self.sprites.remove ( x )
					else :
						x.draw ( )

	def update ( self , event , pos , keys ) :
		pass
